Java JavaScript Python C# C C++ Go Kotlin PHP Swift R Ruby TypeScript Scala SQL Perl rust VisualBasic Matlab Julia

Python Functions → default arguments

Python Functions

default arguments

Python functions offer a powerful feature called default arguments. This allows you to specify default values for function parameters. If a caller doesn't provide a value for a parameter with a default, the function uses the default value. This enhances code flexibility and readability by reducing the number of required arguments in function calls.

Basic Syntax and Mechanism

Default arguments are defined within the function's definition, assigning a value to the parameter directly. The order is crucial: parameters with defaults must come after parameters without defaults.
Python default argument example def greet(name, greeting="Hello"): """Greets a person with a customizable greeting.""" print(f"{greeting}, {name}!") greet("Alice") greet("Bob", "Hi")

Output

Hello, Alice! Hi, Bob!
In this example, `greeting` has a default value of "Hello". The first call omits the `greeting` argument, so the default is used. The second call provides "Hi", overriding the default.

Multiple Default Arguments

You can have multiple parameters with default values:
Python Multiple Default Arguments def describe_pet(animal_type, pet_name, age=3, color="brown"): """Describes a pet with optional age and color.""" print(f"I have a {age}-year-old {color} {animal_type}.") print(f"Its name is {pet_name}.") describe_pet("dog", "Buddy") # Output uses default age and color describe_pet("cat", "Whiskers", 5, "grey") # Overrides defaults describe_pet("bird", "Tweety", color="blue") # Overrides only color

Output

I have a 3-year-old brown dog. Its name is Buddy. I have a 5-year-old grey cat. Its name is Whiskers. I have a 3-year-old blue bird. Its name is Tweety.
Note how the defaults are applied if not provided, and individual defaults can be overwritten selectively.

Important Considerations

Order Matters: Remember, default arguments must follow non-default arguments in the function definition. Trying to place a default argument before a non-default one will raise a `SyntaxError`.
Python default argument def broken_function(greeting="Hello", name): # SyntaxError! print(f"{greeting}, {name}!")
Mutable Default Arguments (Pitfall): Using mutable objects (like lists or dictionaries) as default arguments can lead to unexpected behavior. Because the default is created only once when the function is defined, subsequent calls will modify the same mutable object.
Python default argument def add_item(item, my_list=[]): my_list.append(item) return my_list print(add_item("apple")) # Output: ['apple'] print(add_item("banana")) # Output: ['apple', 'banana'] (Unexpected!)
Note: To avoid this, use `None` as the default and create a new list inside the function if needed.
Python default argument def add_item(item, my_list=None): if my_list is None: my_list = [] my_list.append(item) return my_list print(add_item("apple")) # Output: ['apple'] print(add_item("banana")) # Output: ['banana'] (Correct behavior)
Readability: While default arguments offer great flexibility, overuse can make functions less readable. Strive for a balance: use defaults for truly optional parameters, but keep the function signature concise and understandable. In Summary Default arguments are a valuable tool for creating flexible and user-friendly Python functions. Understanding their behavior, especially regarding the order of parameters and the pitfalls of mutable defaults, is crucial for writing clean and correct code. By judiciously employing default arguments, you can significantly enhance the design and maintainability of your Python programs.

Tutorials